// ws_micro_shop/pages/rider/rider.js
const api = require('../../../ws_micro_shop/utils/api.js');
const app = getApp();
let timer = null; // 取消倒计时
let fresh = null; // 自动刷新 获取订单
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: 0, // 订单类别1.已接单，到店取货中 2.取货配送中 3.已完成 4.已取消
    tabs: ['全部', '未完成', '已完成'],
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-20.png',
      text: '暂无订单',
    },
    tabCurrent: 0,
    list: [],
    showPop: false,
    reason: '',
    rejectID: '', // 拒绝的订单id
    page: 1,
    hasMore: true,
    loaded: false,
    imgUrl: app.imgUrl,
  },

  onHide() {
    timer && clearInterval(timer);
    fresh && clearInterval(fresh);
  },
  onUnload() {
    timer && clearInterval(timer);
    fresh && clearInterval(fresh);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    wx.setNavigationBarTitle({
      title: options.is_online ? '工作中' : '休息中',
    });
    this.setData({
      tabCurrent: Number(options.status),
      status: options.status,
    }, () => {
      wx.getSetting({
        success(res) {
          if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
            wx.getLocation({
              success: function (res) {
                that.setData({
                  latitude: res.latitude,
                  longitude: res.longitude,
                }, () => {
                  that.getList();
                });
              },
              fail: function () {
                wx.navigateBack();
              },
            });
          } else if (res.authSetting['scope.userLocation'] === false) {
            that.setData({
              open_setting: true,
            });
          } else {
            wx.getLocation({
              success: function (res) {
                that.setData({
                  latitude: res.latitude,
                  longitude: res.longitude,
                }, () => {
                  that.getList();
                });
              },
            });
          }
        },
      });
    });
  },

  showPop: function (e) {
    let { showPop } = this.data;
    this.setData({
      showPop: !showPop,
      rejectID: !showPop ? e.currentTarget.dataset.id : '',
    });
  },

  openMap(e) {
    let { lat: latitude = 0, lng: longitude = 0, name, address } = e.currentTarget.dataset;
    wx.openLocation({
      latitude: Number(latitude),
      longitude: Number(longitude),
      name,
      address,
      scale: 18,
    });
  },

  bindContent: function (e) {
    this.setData({
      reason: e.detail.value,
    });
  },

  onTab: function (e) {
    const { index: tabCurrent } = e.currentTarget.dataset;
    this.setData({
      tabCurrent,
      page: 1,
      hasMore: true,
      loaded: false,
      status: tabCurrent,
    }, () => {
      this.getList();
    });
  },

  getList: function () {
    let that = this;
    let { status, page, list: d_list } = this.data;
    timer && clearInterval(timer);
    fresh && clearInterval(fresh);
    function getInfo() {
      app.ws_micro_shoprequest({
        url: api.rider.list,
        data: {
          type: status,
          page,
        },
        success: function (res) {
          wx.stopPullDownRefresh();
          timer && clearInterval(timer);

          if (res.code === 0) {
            let { list=[], shop } = res.data;
            if (page > 1) {
              list = [...d_list, ...list];
            }
              that.setData({
              hasMore: res.data.list.length === 10,
              list,
              loaded: true,
              shop,
            }, () => {
              that.setTimeOver();
              });

          }
        },
      });
    }
    getInfo();
    fresh = setInterval(function () { 
      getInfo();
    }, 30000);
  },

  setTimeOver() {
    let that = this;
    function cutDown() {
      let list = that.data.list;
      for (let i = 0; i < list.length; i++) {
        if (list[i].residue_time) {
          list[i].residue_time--;
          if (list[i].residue_time == 0) {
            that.getList();
            break;
          }
        }
      }
      that.setData({
        list,
      });
    }
    timer = setInterval(function () {
      cutDown();
    }, 1000);
  },

  reject: function() {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.rider.cancel,
      data: {
        id: that.data.rejectID,
        reason: this.data.reason,
      },
      success: function (res) {
        if (res.code === 0) {
          that.setData({
            showPop: false,
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500,
            mask: false,
          });
          setTimeout(function () {
            that.getList();
          }, 1500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500,
            mask: false,
          });
        }
      },
    });
  },

  accept: function (e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '接受订单',
      confirmText: '确认',
      success: function (res) {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: api.rider.receive,
            data: {
              id: e.currentTarget.dataset.id,
            },
            success: function (res) {
              if (res.code === 0) {
                that.getList();
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 1500,
                  mask: false,
                });
              }
            },
          });
        }
      },
    });
  },

  confirm: function(e) {
    let that = this;
    let { id, name = '' } = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: name === 'sendfinish' ? '确认送达?' : '确认取货?',
      confirmText: '确认',
      success: function (res) {
        if (res.confirm) {
          app.ws_micro_shoprequest({
            url: name === 'sendfinish' ? api.rider.confirm : api.rider.pickUp,
            data: {
              id,
            },
            success: function (res) {
              if (res.code === 0) {
                that.getList();
                wx.showToast({
                  title: '确认成功',
                  icon: 'success',
                  duration: 1500,
                  mask: false,
                });
              } else {
                wx.showToast({
                  title: res.msg,
                  icon: 'none',
                  duration: 1500,
                  mask: false,
                });
              }
            },
          });
        }
      },
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: true,
      loaded: false,
    }, () => {
    this.getList();
    });
  },

  onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({
      page: this.data.page + 1,
    }, () => {
      this.getList();
    });
  },

  tel: function (e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel,
      success: () => {},
    });
  },

});